<template>
  <el-container style="flex-direction: column; height: 100vh;">
    <!-- 顶部栏 -->
    <HeaderComponent :userInfo="this.userInfo" />

    <!-- 主内容区 -->
    <el-container style="flex-direction: row; height: 100vh;">
      <!-- 侧边栏 -->
      <SidebarComponent />

      <!-- 公告列表 -->
      <el-main>
        <!-- 顶部功能区 -->
        <div class="toolbar">
          <el-button type="primary" icon="el-icon-plus" @click="showAddDialog">发布公告</el-button>
        </div>

        <el-row :gutter="20">
          <el-col v-for="groupAnnouncement in groupedAnnouncements" :key="groupAnnouncement.date" :span="24">
            <el-card class="date-card">
              <div class="date-title">{{ groupAnnouncement.date }}</div>
              <el-row :gutter="20">
                <el-col v-for="(announcement, index) in groupAnnouncement.announcements" :key="index" :span="8"
                  class="announcement-col">
                  <el-card class="announcement-card">
                    <div class="announcement-header">
                      <span class="announcement-title">{{ announcement.announcementTitle }}</span>
                      <div class="announcement-actions">
                        <el-button type="text" icon="el-icon-edit" @click="editAnnouncement(announcement)"></el-button>
                        <el-button type="text" icon="el-icon-delete"
                          @click="deleteAnnouncement(announcement)"></el-button>
                      </div>
                    </div>
                    <div class="announcement-content">{{ announcement.announcementContent }}</div>
                    <div class="announcement-time">{{ announcement.updateTime.replace("T", " ") }}</div>
                  </el-card>
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>

        <!-- 发布公告弹窗 -->
        <el-dialog title="发布公告" :visible.sync="addDialogVisible" width="500px">
          <el-form :model="newAnnouncement" label-width="80px">
            <el-form-item label="标题">
              <el-input v-model="newAnnouncement.announcementTitle"></el-input>
            </el-form-item>
            <el-form-item label="内容">
              <el-input v-model="newAnnouncement.announcementContent" type="textarea"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleAddAnnouncement">确定</el-button>
          </span>
        </el-dialog>

        <!-- 编辑公告弹窗 -->
        <el-dialog title="编辑公告" :visible.sync="editDialogVisible" width="500px">
          <el-form :model="editAnnouncementData" label-width="80px">
            <el-form-item label="标题">
              <el-input v-model="editAnnouncementData.announcementTitle"></el-input>
            </el-form-item>
            <el-form-item label="内容">
              <el-input v-model="editAnnouncementData.announcementContent" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="是否展示">
              <el-select v-model="editAnnouncementData.isShow" placeholder="请选择">
                <el-option label="展示" :value="1"></el-option>
                <el-option label="不展示" :value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="发布日期">
              <div class="announcement-time" style="font-size: 14px; color: #333;">{{ editAnnouncementData.updateTime.replace("T", " ") }}</div>
            </el-form-item>

          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleEditAnnouncement">确定</el-button>
          </span>
        </el-dialog>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import HeaderComponent from '@/components/property_components/PropertyHeader.vue';
import SidebarComponent from '@/components/property_components/PropertySidebar.vue';
import { parseJwt } from '@/utils/parseJWT';
import service from '@/utils/request';

export default {
  components: {
    HeaderComponent,
    SidebarComponent
  },
  data() {
    return {
      userInfo: {},
      announcements: [],
      addDialogVisible: false, // 发布公告弹窗显示状态
      newAnnouncement: {
        creatorId: '',
        announcementTitle: '',
        announcementContent: '',
      }, // 新公告表单数据

      editDialogVisible: false, // 编辑公告弹窗显示状态
      editAnnouncementData: {
        creatorId: '',
        announcementTitle: '',
        announcementContent: '',
        updateTime: '',
        isShow: '',
      }, // 编辑公告表单数据
    };
  },
  mounted() {
    this.userInfo = parseJwt(localStorage.getItem('token')).payload;
    this.getAnnouncements();
  },
  computed: {
    groupedAnnouncements() {
      const grouped = {};
      // 按日期分组
      this.announcements.forEach(announcement => {
        const date = new Date(announcement.updateTime).toISOString().split('T')[0];
        if (!grouped[date]) {
          grouped[date] = [];
        }
        grouped[date].push(announcement);
      });

      const result = [];
      for (const [date, announcements] of Object.entries(grouped)) {
        result.push({
          date,
          announcements
        });
      }

      // 按日期从近到远排序
      result.sort((a, b) => {
        return new Date(b.date) - new Date(a.date);
      });
      console.log("groupedAnnouncements:", result);
      return result;
    }
  },
  methods: {
    getAnnouncements() {
      service.get(`/api/admin/announcement/getAllAnnouncement`).then((result) => {
        result = result.data;
        if (result.code == 1) {
          console.log("获取公告成功", result.data);
          this.announcements = result.data;
        } else {
          alert(result.msg);
        }
      });
    },
    showAddDialog() {
      this.addDialogVisible = true;
    },
    handleAddAnnouncement() {
      if (!this.newAnnouncement.announcementTitle || !this.newAnnouncement.announcementContent) {
        this.$message.warning('请填写标题和内容');
        return;
      }
      this.newAnnouncement.creatorId = this.userInfo.id;
      console.log("newAnnouncement:", this.newAnnouncement);
      service.post(`/api/admin/announcement/addAnnouncement`, this.newAnnouncement)
        .then((result) => {
          result = result.data;
          if (result.code == 1) {
            this.$message.success('添加公告成功');
            this.getAnnouncements();
            this.addDialogVisible = false;
          } else {
            this.$message.error(result.msg);
          }
        }).catch(error => {
          this.$message.error('添加公告失败');
          console.error(error);
        });
    },
    editAnnouncement(announcement) {
      this.editAnnouncementData = {
        id: announcement.id,
        announcementTitle: announcement.announcementTitle,
        announcementContent: announcement.announcementContent,
        updateTime: announcement.updateTime,
        isShow: announcement.isShow
      };
      this.editDialogVisible = true;
    },
    handleEditAnnouncement() {
      if (!this.editAnnouncementData.announcementTitle && !this.editAnnouncementData.announcementContent) {
        this.$message.warning('请填写标题和内容');
        return;
      }
      service.post(`/api/admin/announcement/updateAnnouncement`, this.editAnnouncementData)
        .then((result) => {
          result = result.data;
          if (result.code == 1) {
            this.$message.success('编辑公告成功');
            this.getAnnouncements(); // 刷新数据
            this.editDialogVisible = false; // 关闭弹窗
          } else {
            this.$message.error(result.msg);
          }
        }).catch(error => {
          this.$message.error('编辑公告失败');
          console.error(error);
        });
    },
    deleteAnnouncement(announcement) {
      this.$confirm(`确认删除公告 "${announcement.announcementTitle}"?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户点击“确定”后执行删除请求
          service.get(`/api/admin/announcement/deleteAnnouncement/${announcement.id}`)
            .then((result) => {
              result = result.data;
              if (result.code == 1) {
                this.$message.success('删除公告成功');
                this.getAnnouncements(); // 刷新数据
              } else {
                this.$message.error(result.msg);
              }
            })
            .catch((error) => {
              this.$message.error('删除公告失败');
              console.error(error);
            });
        })
        .catch(() => {
          // 用户点击“取消”时不执行任何操作
          this.$message.info('已取消删除');
        });
    },
  },
};
</script>

<style>
.toolbar {
  margin-bottom: 20px;
}

.date-card {
  margin-bottom: 20px;
}

.date-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.announcement-col {
  margin-bottom: 20px;
}

.announcement-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  min-height: 200px;
  /* 设置最小高度，确保卡片高度一致 */
}

.announcement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.announcement-title {
  font-size: 16px;
  font-weight: bold;
}

.announcement-actions {
  display: flex;
  gap: 10px;
}

.announcement-content {
  color: #666;
  margin-bottom: 10px;
  flex-grow: 1;
  overflow: hidden;
  /* 防止内容溢出 */
  text-overflow: ellipsis;
  /* 超出部分显示省略号 */
  display: -webkit-box;
  -webkit-line-clamp: 3;
  /* 限制显示行数 */
  -webkit-box-orient: vertical;
}

.announcement-time {
  color: #999;
  font-size: 12px;
}
</style>